﻿using ActionSystem.Core.HitLogic;
using ActionSystem.Core.Ranges;
using ActionSystem.Core.Utils;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ActionSystem.Core.HitLogic
{
    [PoolInitAttribute(typeof(GameObjectPool<CapsuleRangeBoxItem>), 50)]
    public class CapsuleRangeBoxItem : RangeBoxItem
    {
        public override Collider InitCollider()
        {
            return gameObject.AddComponent<CapsuleCollider>();
        }

        protected override void PutBackToPool()
        {
            if(!IsDeleted)
            {
                GameObjectPool<CapsuleRangeBoxItem>.Delete(this);
            }            
        }

        public override void SetRangeShape(IItem item)
        {
            base.SetRangeShape(item);
            CapsuleItem r = item as CapsuleItem;
            if (r != null)
            {
                var cap = hitBox as CapsuleCollider;
                if(cap != null)
                {
                    cap.transform.rotation = Quaternion.Euler(r.rotation);
                    cap.center = Vector3.zero;
                    cap.transform.position = new Vector3(r.offset.x, r.offset.y, r.offset.z);
                    cap.radius = r.radius;
                    cap.height = r.height;
                }
            }
        }

        public override int HitDetect(int unityLayerMask)
        {
            if(value == null || unityLayerMask == 0)
            {
                return 0;
            }
            CapsuleItem cap = value as CapsuleItem;
            if (cap == null)
            {
                return 0;
            }
            Vector3 postion = transform.position;
#if UNITY_EDITOR
            var defaultColor = XMLib.DrawUtility.D.color;
            XMLib.DrawUtility.D.color = Color.yellow;
            XMLib.DrawUtility.D.duration = 1 / 60f;
            var m2 = transform.localToWorldMatrix;
            XMLib.DrawUtility.D.DrawCapsule(cap.height, cap.radius, m2);
            XMLib.DrawUtility.D.color = defaultColor;
#endif
            if (cap.height<2*cap.radius)
            {
                return Physics.OverlapCapsuleNonAlloc(postion, postion, cap.radius, HitResult, unityLayerMask);
            }else
            {
                Vector3 dp = transform.rotation * (Vector3.up * (cap.height - 2 * cap.radius) / 2);
                return Physics.OverlapCapsuleNonAlloc(postion + dp, postion - dp, cap.radius, HitResult, unityLayerMask);                
            }
            
        }
    }
}


